function explicit_step % Solves the heat equation for various M values % diff(u,x,x) = diff(u,t) + f(x,t) for xL < x < xr, 0 < t < tmax % where % u = 0 at x=xL,xR and u = step at a & b at t = 0 % clear all previous variables and plots clear * clf % set parameters N=26; tmax=0.1; xL=0; xR=1; a=0.25; b=0.75; fprintf('\n Solution Computed with N = %3.0f\n\n',N) % calculate exact solution at t=tmax xx=linspace(xL,xR,100); for i=1:100 s=0; for ii=1:50 an=2*(cos(a*pi*ii)-cos(b*pi*ii))/(pi*ii); s=s+an*exp(-pi*pi*ii*ii*tmax)*sin(pi*ii*xx(i)); end; u(i)=s; end; % generate the points along the x-axis, x(1)=xL and x(N+2)=xR x=linspace(xL,xR,N+2); h=x(2)-x(1); % get(gcf) %set(gcf,'Position', [1155 497 575 470]); plotsize(560,725) % calculate the explicit solution using different M values for im=1:3 M=143+im; % generate the points along the t-axis, t(1)=0 and t(M)=tmax t=linspace(0,tmax,M+1); k=t(2)-t(1); lamda=k/h^2; fprintf('\n Lamda = %5.2e\n\n',lamda) ue=explicit2(x,t,N+2,M+1,h,k,lamda); % plot results subplot(3,1,im) plot(x,ue(:,M+1),'r') hold on % define axes used in plot xlabel('x-axis','FontSize',14,'FontWeight','bold') ylabel('Solution','FontSize',14,'FontWeight','bold') % have MATLAB use certain plot options (all are optional) set(gca,'FontSize',14); axis([0 1 0 0.4]); set(gca,'ytick',[0 0.2 0.4]); plot(xx,u,'--k') box on legend([' \lambda = ',num2str(lamda,'%3.3f')],' Exact','Location','South'); set(findobj(gcf,'tag','legend'),'FontSize',12,'FontWeight','bold'); if im==1 say=['Heat Equation: exact vs explicit method at t = ',num2str(tmax,'%3.1f')]; title(say,'FontSize',14,'FontWeight','bold') end; hold off end; % explicit method function UE=explicit2(x,t,N,M,h,k,lamda) UE=zeros(N,M); for i=1:N UE(i,1)=g(x(i)); end; for j=2:M for i=2:N-1 UE(i,j)=lamda*UE(i+1,j-1)+(1-2*lamda)*UE(i,j-1)+lamda*UE(i-1,j-1)-k*f(x(i),t(j-1)); end; end; % subfunction f(x,t) function q=f(x,t) q=0; % subfunction g(x) function q=g(x) q=0.5*(sign(x-0.25)-sign(x-0.75)); % tridiagonal solver function y = tridiag( a, b, c, f ) N = length(f); v = zeros(1,N); y = v; w = a(1); y(1) = f(1)/w; for i=2:N v(i-1) = c(i-1)/w; w = a(i) - b(i)*v(i-1); y(i) = ( f(i) - b(i)*y(i-1) )/w; end; for j=N-1:-1:1 y(j) = y(j) - v(j)*y(j+1); end; % subfunction plotsize function plotsize(width,height) siz=get(0,'ScreenSize'); bottom=max(siz(4)-height-95,1); set(gcf,'Position', [2 bottom width height]);